<?php
/**
 * Created by PhpStorm.
 * User: elk
 * Date: 2022/07/95
 * Time: 2:19 PM
 */

namespace weChat\pay;

use fast\Http;

/**
 * 下发小程序和公众号统一的服务消息
 * @param array $payInfo
 */
class UniformMessage extends Pit
{
    // 接口调用凭证
    public $accessToken = '';

    // 公众号appid
    public $mp_appid = '';

    // 小程序appid
    public $mini_appid = '';

    // 公众号消息模版ID
    public $template_id = '';

    // 公众号模板消息所要跳转的url
    public $url = 'http://weixin.qq.com/download';

    // 公众号模板消息所要跳转的小程序，小程序的必须与公众号具有绑定关系
    public $miniprogram = [];
//[
//    'appid' => $this->mini_appid,
//    'pagepath' => 'pages/index/index?foo=bar',
//]
    // 消息数据
    public $data = [];
//    [
//        "first" => [
//            "value" => "预约通知",
//            "color" => "#173177"
//        ],
//        "keyword1" => [
//            "value" => "进度",
//            "color" => "#173177"
//        ],
//        "keyword2" => [
//            "value" => "日期",
//            "color" => "#173177"
//        ],
//        "remark" => [
//            "value" => "备注",
//            "color" => "#173177"
//        ]
//    ]

    /**
     * 发送公众号消息
     * @param array $payInfo
     */
    public function handle($accessToken)
    {
        $requestData = $this->disposalData();
        $uri ='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send';
        $uri = $uri.'?access_token='.$accessToken;
        $data = $this->toJson($uri, $requestData);

        if (empty($data)) {
            $this->exception('data数据不存在');
        }
        $data = JsonDe($data);
        if ($data['errcode'] == 43004) {
            $this->exception('请先绑定公众号');
            return false;
        }else if ($data['errcode'] != 0) {
            $this->exception('返回状态码非SUCCESS，错误信息:' . $data['errmsg']);
            return false;
        }

        return true;
    }

    /**
     * 整理数据
     */
    protected function disposalData()
    {
        if (empty($this->accessToken)) {
            $this->exception('接口调用凭证不能为空');
        }
        if (empty($this->openid)) {
            $this->exception('接收用户OPENID不能为空');
        }
        if (empty($this->mp_appid)) {
            $this->exception('公众号APPID不能为空');
        }
        if (empty($this->mini_appid)) {
            $this->exception('小程序APPID不能为空');
        }
        if (empty($this->template_id)) {
            $this->exception('公众号消息模版不能为空');
        }
        $data = [
            'access_token' => $this->accessToken,
            'touser' => $this->openid,   //发给谁
            'mp_template_msg' => [
                'appid' => $this->mp_appid,
                'template_id' => $this->template_id,
                'data' => $this->data
            ]
        ];
        if(!empty($this->url)){
            $data['mp_template_msg']['url'] = $this->url;
        }
        // todo 未上线先关闭小程序跳转参数
//        if(!empty($this->miniprogram)){
//            $data['mp_template_msg']['miniprogram'] = $this->miniprogram;
//        }
        return $data;
    }
}